package com.open.loan.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.transformer.StringToInteger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.open.common.utils.HttpContextUtils;
import com.open.common.utils.IPUtils;
import com.open.common.utils.IpInfo;
import com.open.loan.config.BaiduApi.GetAccess_token;
import com.open.loan.domain.req.ReqBaiduApiModel;
import com.open.loan.utils.CookieUtil;
import com.open.loan.utils.HttpUtil;
import com.open.loan.utils.ResponseUtil;
import com.open.system.domain.LoanApplyDO;
import com.open.system.domain.LoanFaceDO;
import com.open.system.domain.LoanFaceLogDO;
import com.open.system.domain.LoanUserDO;
import com.open.system.service.LoanApplyService;
import com.open.system.service.LoanFaceLogService;
import com.open.system.service.LoanFaceService;
import com.open.system.service.LoanUserService;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/moblie")
public class VueBaiduApiPostController {
	
	@Autowired
	private LoanFaceService loanFaceService;
	
	@Autowired
	private LoanApplyService loanApplyService;
	
	@Autowired
	private LoanUserService loanUserService;
	
	@Autowired
	private LoanFaceLogService loanFaceLogService;
	
	@ApiOperation(value="获取随机数字", notes="")
	@RequestMapping(value ="/getBaiduApiCode",method = RequestMethod.POST)
	public ResponseEntity<String> getBaiduApiCode(HttpServletRequest request,HttpServletResponse response){
				try{
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					loanUserDo=loanUserService.get(loanUserDo.getId());
					Map<String, Object> parameters = new HashMap<String, Object>();
					String access_token=GetAccess_token.getAuth();
					String appID=GetAccess_token.APPID;
					parameters.put("access_token",access_token);
					parameters.put("appid",appID);
					String url="https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/sessioncode";
					Object object=HttpUtil.sendBaiduApiPost(url, parameters);
					Map<String, String>map= new HashMap<String, String>();
					JSONObject jsonObject =JSONObject.parseObject(object.toString());
					String code=jsonObject.getString("err_no");
					String msg=jsonObject.getString("err_msg");
					if("0".equals(code)){
						code="200";
						String result=jsonObject.getString("result");
						JSONObject jsonObject2 =JSONObject.parseObject(result);
						String session_id=jsonObject2.getString("session_id");
						CookieUtil.set(response,loanUserDo.getMobile()+"_baiduSession",session_id, 1000*60*5);//5分钟
						String codeNum=jsonObject2.getString("code");
						map.put("number", codeNum);
						
						//日志----开始
						LoanFaceLogDO faceLogDO=new LoanFaceLogDO();
						faceLogDO.setCreateTime(new Date());
						faceLogDO.setPhone(loanUserDo.getMobile());
						faceLogDO.setRealName(loanUserDo.getRealName());
						faceLogDO.setUserId(loanUserDo.getId());
						faceLogDO.setRemark1("已获取语音检验码:"+codeNum);//成功/失败原因
						faceLogDO.setStatus("成功");
						faceLogDO.setRemark2(loanUserDo.getRemark3());//店铺名称
						faceLogDO.setRemark3(loanUserDo.getRemark2());//店铺ID
						System.out.println("IP="+IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));
						faceLogDO.setRemark4(IPUtils.getIpAddr(request));//认证城市
						loanFaceLogService.save(faceLogDO);
						//日志----结束
					}
					ResponseUtil.toWrite(code,msg,map, response);
					return null;
				} catch (Exception e) {
					e.printStackTrace();
					ResponseUtil.toWrite("202","调用接口失败",null, response);
					return null;
				}
				
		}
	
	//--h5人脸校验---------------------------------------------------------------------------------------------
	@ApiOperation(value="视频活体校验", notes="")
	@RequestMapping(value ="/getBaiduApiVideo",method = RequestMethod.POST)
	public ResponseEntity<ReqBaiduApiModel> getBaiduApiVideo(@RequestBody ReqBaiduApiModel model, HttpServletRequest request,HttpServletResponse response){
		
					if(model==null){
						ResponseUtil.toWrite("105","视频数据传输为空",null, response);
						return null;
					}
					if(model.getVideo_base64()==null || model.getVideo_base64()==""){
						ResponseUtil.toWrite("105","视频数据传输为空",null, response);
						return null;
					}
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					loanUserDo=loanUserService.get(loanUserDo.getId());
					//日志----开始
					LoanFaceLogDO faceLogDO=new LoanFaceLogDO();
					faceLogDO.setCreateTime(new Date());
					faceLogDO.setPhone(loanUserDo.getMobile());
					faceLogDO.setRealName(loanUserDo.getRealName());
					faceLogDO.setUserId(loanUserDo.getId());
					faceLogDO.setRemark2(loanUserDo.getRemark3());//店铺名称
					faceLogDO.setRemark3(loanUserDo.getRemark2());//店铺ID
					faceLogDO.setRemark4(IPUtils.getIpAddr(request));//认证城市
					//日志----结束
					
					
					//---
					Map<String, Object> map=new HashMap<String, Object>();
					map.put("userId",loanUserDo.getId());
					//申请认证修改------开始
					LoanFaceDO loanFaceDO=new LoanFaceDO();
					LoanApplyDO applyDO=null;
					List<LoanApplyDO>applyDOs=loanApplyService.list(map);
					if(applyDOs!=null && applyDOs.size()>0){
						applyDO=applyDOs.get(0);
						applyDO.setFaceAuth("1");// 一进来就是审核中    ['0待完善', '1审核中', '2认证成功', '3认证失败']
						loanApplyService.update(applyDO);
					}else {
						faceLogDO.setRemark1("还未实名");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						ResponseUtil.toWrite("209","请先认证银行卡信息",null, response);
						return null;
					}
					//申请认证修改------结束
					//----
				try{
					loanUserDo=loanUserService.get(loanUserDo.getId());
					Map<String, Object> parameters = new HashMap<String, Object>();
					String access_token=GetAccess_token.getAuth();
					Cookie cookie_session_id = CookieUtil.get(request,loanUserDo.getMobile()+"_baiduSession");
					if(cookie_session_id==null){
						applyDO.setFaceAuth("3");
						applyDO.setLoanScore("数字已过期");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("数字已过期");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite("204","数字已过期",null, response);
						return null;
					}
					if(cookie_session_id.getValue()==null){
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore("数字已过期");
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("数字已过期");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite("204","数字已过期",null, response);
						return null;
					}
					
					parameters.put("access_token",access_token);
					parameters.put("session_id",cookie_session_id.getValue());
					parameters.put("video_base64",model.getVideo_base64());
					String url="https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/verify";
					Object object=HttpUtil.sendBaiduApiPost(url, parameters);
					JSONObject jsonObject =JSONObject.parseObject(object.toString());
					String code=jsonObject.getString("err_no");
					String msg=jsonObject.getString("err_msg");
					if("0".equals(code)){
						code="200";
						String result=jsonObject.getString("result");
						JSONObject jsonObject2 =JSONObject.parseObject(result);
						
						String score=jsonObject2.getString("score");//库值
						loanFaceDO.setUserId(loanUserDo.getId());
						loanFaceDO.setRealName(loanUserDo.getRealName());
						loanFaceDO.setCreateTime(new Date());
						loanFaceDO.setScore(score);
						//--------------thresholds-------------------------------------------
						String thresholds=jsonObject2.getString("thresholds");//数组
						JSONObject frr_1eJson=JSONObject.parseObject(thresholds);
						String frr_1e_4=frr_1eJson.getString("frr_1e-4");//库值3
						String frr_1e_3=frr_1eJson.getString("frr_1e-3");//库值4
						String frr_1e_2=frr_1eJson.getString("frr_1e-2");//库值5
						loanFaceDO.setFrr1e2(frr_1e_2);
						loanFaceDO.setFrr1e3(frr_1e_3);
						loanFaceDO.setFrr1e4(frr_1e_4);
						//--------------code-----------------------------------------
						String returnCode=jsonObject2.getString("code");//数组
						JSONObject codeJson=JSONObject.parseObject(returnCode);
						String create=codeJson.getString("create");//库值6
						String identify=codeJson.getString("identify");//库值7
						loanFaceDO.setCreate(create);
						loanFaceDO.setIdentify(identify);
						if(!create.equals(identify)){
							applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
							applyDO.setLoanScore("语音读取不正确");
							loanApplyService.update(applyDO);
							//日志新增--开始
							faceLogDO.setRemark1("语音读取不正确");//成功/失败原因
							faceLogDO.setStatus("失败");
							loanFaceLogService.save(faceLogDO);
							//日志新增--结束
							ResponseUtil.toWrite("209","语音读取不正确",null, response);
							return null;
						}
						//--------------pic_list--------------------------------------------
						String pic_list=jsonObject2.getString("pic_list");//数组
						JSONArray pic_listArray=JSONArray.parseArray(pic_list);
						for (int i = 0; i <pic_listArray.size(); i++) {
							Object jsonStr=pic_listArray.get(i);
							JSONObject jsonStr2 =JSONObject.parseObject(jsonStr.toString());
							String face_id=jsonStr2.getString("face_id");//库值2个
							String pic=jsonStr2.getString("pic");//库值2个
							if(i==0){
								loanFaceDO.setFaceId1(face_id);
								loanFaceDO.setPic1(pic);
							}else if (i==1) {
								loanFaceDO.setFaceId2(face_id);
								loanFaceDO.setPic2(pic);
							}else if (i==2) {
								loanFaceDO.setFaceId3(face_id);
								loanFaceDO.setPic3(pic);
							}
						}
						//申请认证修改------开始
						applyDO.setFaceAuth("2");//['0待完善', '1审核中', '2认证成功', '3认证失败']
						loanFaceDO.setStatus("2");//1 认证生成
						loanFaceDO.setStatus("2");
						loanApplyService.update(applyDO);
						loanFaceService.save(loanFaceDO);
						
						//申请认证修改------结束
						
					}else if("216506".equals(code)){
						msg="redis操作失败";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("redis操作失败");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216505".equals(code)){
						msg="redis连接失败";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("redis连接失败");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216430".equals(code)){
						msg="face 服务异常";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("face 服务异常");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216502".equals(code)){
						msg="当前会话已失效";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("当前会话已失效");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216501".equals(code)){
						msg="没有找到人脸";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("没有找到人脸");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216508".equals(code)){
						msg="没有找到视频信息";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("没有找到视频信息");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216434".equals(code)){
						msg="活体检测失败";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("活体检测失败");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216908".equals(code)){
						msg="光照不足或人脸模糊";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("光照不足或人脸模糊");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216507".equals(code)){
						msg="视频中有多张人脸";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("视频中有多张人脸");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216433".equals(code)){
						msg="视频解析服务发生错误";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("视频解析服务发生错误");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216432".equals(code)){
						msg="视频解析服务调用失败";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("视频解析服务发生错误");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216431".equals(code)){
						msg="语音识别服务异常";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("语音识别服务异常");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}else if("216500".equals(code)){
						msg="验证码位数错误";
						applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setLoanScore(msg);
						loanApplyService.update(applyDO);
						//日志新增--开始
						faceLogDO.setRemark1("验证码位数错误");//成功/失败原因
						faceLogDO.setStatus("失败");
						loanFaceLogService.save(faceLogDO);
						//日志新增--结束
						ResponseUtil.toWrite(code,msg,null, response);
						return null;
					}
					//日志新增--开始
					faceLogDO.setRemark1("人脸认证成功");//成功/失败原因
					faceLogDO.setStatus("成功");
					loanFaceLogService.save(faceLogDO);
					//日志新增--结束
					ResponseUtil.toWrite(code,msg,null, response);
					return null;
				} catch (Exception e) {
					e.printStackTrace();
					applyDO.setFaceAuth("3");// ['0待完善', '1审核中', '2认证成功', '3认证失败']
					applyDO.setLoanScore("调用接口失败");
					loanApplyService.update(applyDO);
					//日志新增--开始
					faceLogDO.setRemark1("调用接口失败");//成功/失败原因
					faceLogDO.setStatus("失败");
					loanFaceLogService.save(faceLogDO);
					//日志新增--结束
					ResponseUtil.toWrite("202","调用接口失败",null, response);
					return null;
				}
				
		}

}
